﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TDgameTuret : MonoBehaviour
{
    public Transform rotatorObj;
    //public Transform rotatorObjVertical;
    public Transform rayStart;
    public Transform rayEnd;
    public Transform firePoint;
    public GameObject bullet;
    public GameObject fireFx;
    public List<GameObject> enemyList = new List<GameObject>();
    private GameObject target = null;
    private float timer = 0;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (enemyList.Count > 0) 
        {
            for (int i = 0; i < enemyList.Count; i++)
            {
                if (target == null)
                {
                    target = enemyList[i];
                    continue;
                }
                if (enemyList[i]!=null&&Vector3.Distance(target.transform.position,transform.position)>Vector3.Distance(enemyList[i].transform.position,transform.position))
                {
                    target = enemyList[i];
                }
            }
        }
        if(target==null)
        {
            return;
        }


        //计算方向
        Vector3 direction = target.transform.position - transform.position;
        //水平旋转
        direction = Quaternion.AngleAxis(90,Vector3.up) * direction;  //加上模型自生的旋转偏移量,通过旋转向量实现
        rotatorObj.rotation = Quaternion.Slerp(rotatorObj.rotation,
            Quaternion.LookRotation(direction),
            0.1f
            );


        Ray ray = new Ray(rayEnd.position, (rayEnd.position - rayStart.position) * 50);
        RaycastHit rayHitInfo;
        Physics.Raycast(ray, out rayHitInfo);
        if (rayHitInfo.distance<50||rayHitInfo.collider.tag.Equals("Enemy"))
        {
            timer += Time.deltaTime;
            if(timer>1)
            {
                if(fireFx!=null)
                {
                    Instantiate(fireFx,firePoint.position, Quaternion.AngleAxis(90f, Vector3.up * 90)* firePoint.rotation );
                }
                var bu=Instantiate(bullet, firePoint.position, Quaternion.AngleAxis(90f,Vector3.up*90)* firePoint.rotation );
                bu.transform.Rotate(Vector3.up * 90f);
                timer = 0;
            }
        }
    }

}
